import { floatSub,
    floatAdd} from "@/api/utils"
// 调入api 浮点数相加，相减的方法
export const change_logo = (cartItem, shopcarData = []) => {
    const {id} = cartItem
    let index = shopcarData.findIndex((item) => item.id == id)
    shopcarData[index].isChecked = ! shopcarData[index].isChecked
    return shopcarData
}

export const allmoney = (shopcarData) => {
    let arr = shopcarData.filter(item => item.isChecked)
    return arr.reduce((sum, cur) =>  floatAdd(sum,cur.price*cur.num), 0)
}

export const less_num = (id, shopcarData) => {
    let index = shopcarData.findIndex((item) => item.id == id)
    shopcarData[index].isChecked = true;

    // 业务，当商品的num变为1时，不能再减少，把按钮改为disabel:false
    if (shopcarData[index].num == 1) {
            shopcarData[index].isChecked = false
            return shopcarData
    }
    shopcarData[index].num--;
    if(shopcarData[index].num == 1)  shopcarData[index].isChecked = false
    return shopcarData
}

export const add_num = (id, shopcarData) => {
    let index = shopcarData.findIndex((item) => item.id == id)

    // 业务逻辑 点击数量增加后，isChecked改为true
    shopcarData[index].isChecked = true;
    shopcarData[index].num++;
    return shopcarData
}

export const change_num = (data,shopcarData) => {

    let {num,id} =data
    let index = shopcarData.findIndex((item) => item.id == id)
    
    shopcarData[index].num = num
    shopcarData[index].isChecked = true
    return shopcarData
}

export const allSelected = (shopcarData) => {
    // 判断如果index == -1 则全选
    let index = shopcarData.findIndex((item) => !item.isChecked)
    if(index == -1) return true
}

export const SelectedAll = (shopcarData) =>{
    let index = shopcarData.findIndex((item) => !item.isChecked) 
    if(index == -1) {    // 表示全选
        shopcarData.map(item => 
        item.isChecked = !item.isChecked)
    }
    else{ // 没选或部分选
        shopcarData.map(item => 
          item.isChecked = true)
    }
    return shopcarData
}

export const goToShopCar = (data,shopCarData) =>{
    return shopCarData;
}

export const deleteItem = (id,data) =>{
    let index = data.findIndex(item => item.id == id)
    data.splice(index,1)
    return data
}

// 详情页点击进入购物车
export const goToShopCar_btn = (data,shopCarData) =>{
    let {id} = data
    let index = shopCarData.findIndex(item => item.id == id)

    if(index == -1){
        shopCarData.push(data)
        console.log(shopCarData);
        return shopCarData
    }
   return shopCarData
}

// tabbar 的总数量
export const totalnum = (data) =>{
    let num = data.reduce((acc,item) => acc+item.num,0)
    return num
}